package com.vanysoft.framework.kaptcha;

import com.google.code.kaptcha.impl.DefaultKaptcha;

import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;

/**
 * @author qi_ma
 */
public class KaptchaServlet extends HttpServlet implements Servlet {

    private static final long serialVersionUID = 394217830295340575L;
    private final DefaultKaptcha kaptcha;

    KaptchaServlet(DefaultKaptcha kaptcha) {
        this.kaptcha = kaptcha;
    }

    @Override
    public void init(ServletConfig conf) throws ServletException {
        super.init(conf);
        ImageIO.setUseCache(false);
    }

    /** */
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setDateHeader("Expires", 0);
        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
        resp.setHeader("Pragma", "no-cache");
        resp.setContentType("image/jpeg");
        String capText = kaptcha.createText();
        req.getSession().setAttribute(kaptcha.getConfig().getSessionKey(), capText);
        req.getSession().setAttribute(kaptcha.getConfig().getSessionDate(), new Date());
        BufferedImage bi = kaptcha.createImage(capText);
        ServletOutputStream out = resp.getOutputStream();
        ImageIO.write(bi, "jpg", out);
    }
}
